package com.framework.minio;

import io.minio.*;
import io.minio.errors.*;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static java.lang.System.out;

@Slf4j
@Component
public class MinioUtil {

    @Autowired
    private MinioProperties properties;

    @Autowired
    private MinioClient minioClient;

    /**
     * 判断bucket是否存在，不存在则创建
     */
    public boolean isExistBucket(String bucketName){
        try {
            return minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        }catch (Exception e){
            e.printStackTrace();
            log.info("bucket exit, {}",e);
        }
        return false;
    }

    /**
     * 返回的是完整 url，可以通过浏览器直接访问
     */
    public String uploadReturnUrl(MultipartFile file, String bucketName) {
        return properties.getEndpoint() + "/" + bucketName + "/" + this.uploadReturnObject(file, bucketName);
    }

    /**
     * 通过完整的文件名，即上传后的文件名访问，并非上传前的文件名
     */
    public String uploadReturnObject(MultipartFile file, String bucketName) {
        assertBucketExist(bucketName);

        // bucket 存在则可以上传
        return upload(file, bucketName);
    }

    private void assertBucketExist(String bucketName) {
        boolean isBucketExist;
        // 1. 该项目检查 bucket 是否存在
        List<String> existBucket = new ArrayList<>();
        existBucket.addAll(properties.getPublicBucket());
        existBucket.addAll(properties.getPrivateBucket());
        isBucketExist = existBucket.contains(bucketName);
        if (!isBucketExist) {
            throw new RuntimeException("上传失败，bucket 不存在");
        }

        // 2. minio 检查 bucket 是否存在
        isBucketExist = isExistBucket(bucketName);
        if (!isBucketExist) {
            throw new RuntimeException("上传失败，bucket 不存在");
        }
    }

    private String upload(MultipartFile file, String bucketName) {
        assertBucketExist(bucketName);

        String fileName = file.getOriginalFilename();
        String[] split = fileName.split("\\.");
        if (split.length > 1) {
            fileName = split[0] + "_" + System.currentTimeMillis() + "." + split[1];
        } else {
            fileName = fileName + System.currentTimeMillis();
        }
        InputStream in = null;
        try {
            in = file.getInputStream();
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(fileName)
                    .stream(in, in.available(), -1)
                    .contentType(file.getContentType())
                    .build()
            );
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return fileName;
    }

    /**
     * 下载文件
     */
    public ResponseEntity<byte[]> download(String fileName, String bucketName) {
        assertBucketExist(bucketName);
        ResponseEntity<byte[]> responseEntity = null;
        InputStream in = null;
        ByteArrayOutputStream out = null;
        try {
            in = minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(fileName).build());
            out = new ByteArrayOutputStream();
            IOUtils.copy(in, out);
            //封装返回值
            byte[] bytes = out.toByteArray();
            HttpHeaders headers = new HttpHeaders();
            try {
                headers.add("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            headers.setContentLength(bytes.length);
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setAccessControlExposeHeaders(Arrays.asList("*"));
            responseEntity = new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseEntity;
    }
    public InputStream downloadOutputStream(String fileName, String bucketName) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        assertBucketExist(bucketName);
        InputStream in = null;
        in = minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(fileName).build());
        return in;
    }


    /**
     * 批量删除文件对象
     */
    public Iterable<Result<DeleteError>> removeObjects(String bucketName, List<String> objects) {
        List<DeleteObject> dos = objects.stream().map(e -> new DeleteObject(e)).collect(Collectors.toList());
        Iterable<Result<DeleteError>> results = minioClient.removeObjects(RemoveObjectsArgs.builder().bucket(bucketName).objects(dos).build());
        return results;
    }

}
